package com.zg.ktcomwan

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Html
import android.view.MenuItem
import android.view.View
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.ui.NavigationUI
import com.google.android.material.appbar.AppBarLayout
import com.jeremyliao.liveeventbus.LiveEventBus
import com.zg.core.base.SHNavHostFragment
import com.zg.core.ext.logI
import com.zg.ktcomwan.databinding.ActivityHomeBinding
import com.zg.ktcomwan.fragment.WebFragment
import com.zg.ktcomwan.utils.StatusBarUtil
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.common_tbar.*

/***
 * 1.显示首页数据(最新项目和文章，不要置顶)、项目、广场三个tab就行
 * 2.增加下拉刷新和进入界面时的动画
 * 3.paging3上拉加载更多是不需要处理的
 * 4.AgentWeb githup地址：https://hub.fastgit.org/Justson/AgentWeb https://segmentfault.com/a/1190000039663918
 * 5.LiveEventBus 消息组件 https://blog.csdn.net/Vaccae/article/details/119881269
 * 6.
 */
class HomeActivity : AppCompatActivity() {
    lateinit var mNavController: NavController

    @SuppressLint("RestrictedApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityHomeBinding =
            DataBindingUtil.setContentView(this, R.layout.activity_home)
        StatusBarUtil().setColor(this, resources.getColor(R.color.qc_green), 0)
        val navController: NavController =
            Navigation.findNavController(this, R.id.nav_host_fragment);
        mNavController = navController
        NavigationUI.setupWithNavController(binding.navView, navController)
        //重写导航的跳转
        nav_view.setOnNavigationItemSelectedListener {
            common_title.text = it.title
            lastTitle = it.title.toString()
            navController.navigate(it.itemId)
            true
        }

        iv_arrow.setOnClickListener {
            val canBack = (getCurrentFragment() as WebFragment).agentWeb.back()
            if (canBack)
                return@setOnClickListener

            val fragment: SHNavHostFragment? =
                supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as SHNavHostFragment?
            if (getCurrentFragment() is WebFragment && fragment != null) {
                val a =
                    fragment.childFragmentManager.getBackStackEntryAt(fragment.childFragmentManager.backStackEntryCount - 1)
                fragment.childFragmentManager.popBackStack(
                    "${a.name}",
                    FragmentManager.POP_BACK_STACK_INCLUSIVE
                )
            }
            common_title.text = lastTitle
            iv_arrow.visibility = View.GONE
            nav_view.visibility = View.VISIBLE

            //增加滑动效果
            val layoutParams = (main_bar as Toolbar).layoutParams as AppBarLayout.LayoutParams
            layoutParams.scrollFlags =
                AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
            (main_bar as Toolbar).layoutParams = layoutParams
        }

        navController.addOnDestinationChangedListener { controller, destination, arguments ->
            if (destination.id == R.id.navigation_welcome) {
                nav_view.visibility = View.GONE
                main_bar.visibility = View.GONE
            }

            if (destination.id == R.id.navigation_article) {
                /*val fragment: SHNavHostFragment? =
                    supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as SHNavHostFragment?

                logI("${fragment!!.childFragmentManager.backStackEntryCount}")
                logI("${controller.backStack.last.destination}")
                logI("${controller.backStack.first.destination}")



                if (getCurrentFragment() is WelcomeFragment && fragment != null) {
                    val a =
                        fragment.childFragmentManager.getBackStackEntryAt(fragment.childFragmentManager.backStackEntryCount - 1)
                    fragment.childFragmentManager.popBackStack(
                        "${a.name}",
                        FragmentManager.POP_BACK_STACK_INCLUSIVE
                    )
                }*/

                //navController.popBackStack(R.id.navigation_welcome, true)
                nav_view.visibility = View.VISIBLE
                main_bar.visibility = View.VISIBLE
            }



            if (destination.id == R.id.navigation_web) {
                logI("title==${arguments?.getString("title")}")
                common_title.text = Html.fromHtml(arguments?.getString("title"))
                common_title.requestFocus()
                iv_arrow.visibility = View.VISIBLE
                nav_view.visibility = View.GONE

                //禁止掉滑动效果
                val layoutParams = (main_bar as Toolbar).layoutParams as AppBarLayout.LayoutParams
                layoutParams.scrollFlags = 0
                (main_bar as Toolbar).layoutParams = layoutParams
                //lastTitle = controller.currentDestination!!.label.toString()
                //controller.previousBackStackEntry.
                //logI("${getCurrentFragment()?.childFragmentManager?.primaryNavigationFragment}")
                //getCurrentFragment()!!.targetFragment!!.childFragmentManager.primaryNavigationFragment
            }
        }

        /*navController.addOnDestinationChangedListener { controller, destination, arguments ->
            val fragment: SHNavHostFragment? =
                supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as SHNavHostFragment?
            logI("setOnNavigationItemSelectedListener=======${getCurrentFragment()}")

            if (getCurrentFragment() is WebFragment && fragment != null) {
                *//*logI("setOnNavigationItemSelectedListener id=${R.id.navigation_web} ${fragment1?.id} ${fragment?.childFragmentManager?.primaryNavigationFragment}")
                fragment.childFragmentManager.beginTransaction()
                    .remove(fragment.childFragmentManager.primaryNavigationFragment!!).commit()
                logI("setOnNavigationItemSelectedListener  ${fragment.childFragmentManager.backStackEntryCount + 1}-${getCurrentFragment()!!.tag}")*//*

                val a =
                    fragment.childFragmentManager.getBackStackEntryAt(fragment.childFragmentManager.backStackEntryCount - 1)
                logI("zxd", "a==========id:${a.id}  name:${a.name}")

                //因为只是根据backStackEntryCount的数量来决定 名称的话，前面的那个数字对不上。
                //"${fragment.childFragmentManager.backStackEntryCount + 1}-${getCurrentFragment()!!.tag}",
                fragment.childFragmentManager.popBackStack(
                    "${a.name}",
                    FragmentManager.POP_BACK_STACK_INCLUSIVE
                )

                *//*for (i in 0 until fragment.childFragmentManager.fragments.size) {
                    logI("遍历${fragment.childFragmentManager.fragments[i].tag}")
                }*//*
            }
        }*/
        //initTbar()

        LiveEventBus
            .get("textChange", String::class.java)
            .observe(this, object : Observer<String?> {
                override fun onChanged(@Nullable s: String?) {
                    if (!common_title.text.equals(s)) {
                        if (s!!.contains("-玩Android - wanandroid.com"))
                            common_title.text = s.replace("-玩Android - wanandroid.com", "")
                        else
                            common_title.text = s
                        common_title.requestFocus()
                    }
                }
            })
    }

    private fun getCurrentFragment(): Fragment? {
        val fragment: SHNavHostFragment? =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as SHNavHostFragment?
        return fragment!!.getChildFragmentManager().getPrimaryNavigationFragment()
    }

    private fun initTbar() {
        setSupportActionBar(main_bar as Toolbar)
        val actionBar = supportActionBar
        actionBar!!.setDisplayShowTitleEnabled(false)
        actionBar!!.setDisplayHomeAsUpEnabled(true)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            //finish()
            //java.lang.IllegalArgumentException: Navigation action/destination com.zg.ktcomwan:id/goWeb cannot be found from the current destination Destination(com.zg.ktcomwan:id/navigation_web) label=网页 class=com.zg.ktcomwan.fragment.WebFragment
            //把ArticleAdapter中的点击事件修改为Navigation.findNavController(it).navigate(R.id.navigation_web, bundle)
            val fragment: SHNavHostFragment? =
                supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as SHNavHostFragment?
            if (getCurrentFragment() is WebFragment && fragment != null) {
                val a =
                    fragment.childFragmentManager.getBackStackEntryAt(fragment.childFragmentManager.backStackEntryCount - 1)
                fragment.childFragmentManager.popBackStack(
                    "${a.name}",
                    FragmentManager.POP_BACK_STACK_INCLUSIVE
                )
            }
        }
        return super.onOptionsItemSelected(item)
    }

    companion object {
        var lastTitle = "首页"
    }

    override fun onBackPressed() {
        //如果是 网页界面，有层级的先要退光层级网页，才能退出。否则是会到上一层导航到网页的界面
        if (getCurrentFragment() is WebFragment) {
            val canBack = (getCurrentFragment() as WebFragment).agentWeb.back()
            if (canBack) {
                //donothing
            } else {
                iv_arrow.performClick()
            }
            return
        }

        //返回键和底部导航键的关系，如果不是首页，需要切换到首页才能退出
        if (nav_view.selectedItemId != R.id.navigation_article) {
            mNavController.navigate(R.id.navigation_article)
            common_title.text = "首页"
            iv_arrow.visibility = View.GONE
            nav_view.visibility = View.VISIBLE

            //增加滑动效果
            val layoutParams = (main_bar as Toolbar).layoutParams as AppBarLayout.LayoutParams
            layoutParams.scrollFlags =
                AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
            (main_bar as Toolbar).layoutParams = layoutParams
            return
        }
        super.onBackPressed()
        finish()
    }

    fun initView() {
        nav_view.visibility = View.VISIBLE
        main_bar.visibility = View.VISIBLE
    }
}